/*
 * CoverFlowNode.fx
 *
 * Created on Mar 29, 2010, 2:27:43 PM
 */

package fxgreader.components;
import javafx.scene.CustomNode;
import javafx.animation.Timeline;
import javafx.scene.input.MouseEvent;
import javafx.io.http.HttpRequest;
import fxgreader.FileUtil;
import java.io.File;
import java.lang.Exception;
import javafx.animation.Interpolator;
import javafx.geometry.HPos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ProgressBar;
import javafx.scene.effect.PerspectiveTransform;
import javafx.scene.effect.Reflection;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import fxgreader.Resources;
import javafx.scene.Cursor;

/**
 * @author perkintang
 */

public class ImageCoverFlowNode extends CoverFlowNode {

public var backupImage : String = Resources.text;
public var onTooSmall : function(node : ImageCoverFlowNode);
public var timeline : Timeline;
var image_width : Number;
var image_height : Number;
public var fixed_width : Number;
public var fixed_height : Number;
var getRequest: HttpRequest;
function buildRequest(){
    getRequest = HttpRequest {

    location: bind imageURL;

    onToRead: function(bytes: Long) {
        if (bytes < 0) {
            println("onToRead - Content length not specified by server; bytes: {bytes}");
            totle = 10000;
        } else {
            totle = bytes + 10;
//            println("onToRead - total number of content bytes to read: {bytes}");
        }
    }

    onRead: function(bytes: Long) {
        // The toread variable is non negative only if the server provides the content length
        progress = bytes;
    }

    onInput: function(is: java.io.InputStream) {
        // use input stream to access content here.
        // can use input.available() to see how many bytes are available.
        try {
            FileUtil.saveToFile(is,new File("./{cacheFileName}"));
        } catch(e : Exception){
            e.printStackTrace();
        }
        finally {
            is.close();
        }
    }

    onException: function(ex: java.lang.Exception) {
        imageURL = backupImage;
        image = Image{
                    smooth: false
                    preserveRatio : true;
                    url : imageURL
                    backgroundLoading:true
                 };
        image_width = image.width;
        image_height = image.height;
        fixed_height = 0;
        fixed_width = 0;
        showView();
    }

    onDoneRead: function() { 
//        println("onDoneRead")
    }
    onDone: function() {
            imageURL = "file:///{FileUtil.getPath(cacheFileName)}";
            image = Image{
                    smooth: false
                    preserveRatio : true;
                    url : imageURL
//                    backgroundLoading:true;
                 };
            image_width = image.width;
            image_height = image.height;
            println("onDone : {image.width} x {image.height} pic");
            if(image_width < 50 or image_height < 50){
                imageURL = backupImage;
                image = Image{
                    smooth: false
                    preserveRatio : true;
                    url : imageURL
                    backgroundLoading:true;
                 };
                 image_width = image.width;
                 image_height = image.height;
                 fixed_height = 0;
                 fixed_width = 0;
                 onTooSmall(this);
            }else{
                if(image_width > image_height){
                    image = Image{
                        width:fixed_width
                        smooth: false
                        preserveRatio : true;
                        url : imageURL
                        backgroundLoading:true;
                    };
                }else{
                    image = Image{
                        height:fixed_height
                        smooth: false
                        preserveRatio : true;
                        url : imageURL
                        backgroundLoading:true;
                    };
                }
            }
            showView();
            };

};
}
public function showView(){
     progress = totle;
//     println("onDone : {image.width} x {image.height} pic");
     vbimage.content = [];
     vbimage = VBox{
          translateX : bind ori_width/2 - image.width/2;
          translateY : bind ori_height/2 - image.height/2;
          spacing: 20
          nodeHPos:HPos.CENTER
          content:[imageview]
     };
     //release loading image
     delete vbloading from group.content;
     vbloading = null;
     progressBar = null;
     group.content = [background];
     insert vbimage into group.content;
}
public var image : Image;
var vbimage : VBox;
public var cacheFileName : String;
public var imageURL : String = "" on replace{
//        println("{imageURL}");
        if(not imageURL.startsWith("file:///")){
            cacheFileName = imageURL.substring(imageURL.indexOf("/")+1);
            cacheFileName = cacheFileName.replaceAll("(/|\\?)", "");
            //incase if file name is too long
            if(cacheFileName.length() > 100){
                  cacheFileName = cacheFileName.substring(cacheFileName.length()-100);
            }
            if(FileUtil.fileExist(cacheFileName)){
                  imageURL = "file:///{FileUtil.getPath(cacheFileName)}";
                  image = Image{
                        smooth: false
                        preserveRatio : true;
                        url : imageURL
                  };
                  image_width = image.width;
                  image_height = image.height;
                  image = null;
                  if(image_width < 50 or image_height < 50){
                     imageURL = backupImage;
                     fixed_height = 0;
                     fixed_width = 0;
                     onTooSmall(this);
                 }
            }
        }
};
var imageview : ImageView  = ImageView {
                                    image:  bind image
                                    cache : true
                                };
var totle : Integer = 10000;
var progress = 0 on replace{
};
var progressBar = ProgressBar {
	progress: bind ProgressBar.computeProgress( totle, progress )
};
var vbloading : VBox;
override public function release(){
    getRequest.stop();
    getRequest = null;
    delete vbimage from group.content;
    image = null;
    imageview.image = null;
    vbimage.content = [];
    vbimage = null;
    //release loading image
    delete vbloading from group.content;
    vbloading = null;
    progressBar = null;
    group.content = [background];
}
override public function load():Void{
    if(image != null){
            return;
    }
    if(imageURL.startsWith("http://") or imageURL.startsWith("https://")){
        //requesting, do nothing
        if(getRequest != null){
            return;
        }
        progressBar = ProgressBar {
            progress: bind ProgressBar.computeProgress( totle, progress )
        };
        vbloading = VBox{
              translateX : bind (ori_width - vbloading.layoutBounds.width)/2 - vbloading.layoutBounds.minX;
              translateY : bind ori_height/2 - (100 + 20)/2;
              spacing: 20
              nodeHPos:HPos.CENTER
              content : [progressBar];
          };
        group.content = [background];
        insert vbloading into group.content;
        buildRequest();
        getRequest.start();

    }else{
//        println("fixed_width : {fixed_width}");
        if(image_width > image_height){
            image = Image{
                width: fixed_width
                smooth: false
                preserveRatio : true;
                url : imageURL
                backgroundLoading:true;
            };
        }else{
            image = Image{
                height: fixed_height
                smooth: false
                preserveRatio : true;
                url : imageURL
                backgroundLoading:true;
            };
        }
        vbimage = VBox{
              translateX : bind ori_width/2 - image.width/2;
              translateY : bind ori_height/2 - image.height/2;
              spacing: 20
              nodeHPos:HPos.CENTER
              content:[imageview]
        };
        group.content = [background];
        insert vbimage into group.content;
    }
}
}